package com.neborosoft.lib.collections.stack;

/**
 * Created with IntelliJ IDEA.
 * User: CM
 * Date: 24.11.12
 * Time: 23:09
 * To change this template use File | Settings | File Templates.
 */
public class LimitedStack<T> implements Stack<T> {
    private Object[] items;
    private int size = 0;
    private int maxSize;

    public LimitedStack(int maxSize) {
        this.maxSize = maxSize;
        items = new Object[maxSize];
    }

    public T get(int index){
        return (T)items[index];
    }

    public Object[] asArray(){
        return items;
    }

    @Override
    public void push(T value) {
        if(size == maxSize){
            throw new StackOverflowException();
        }
        items[size++] = value;
    }

    @Override
    public T pop() {
        if(isEmpty()){
            throw new EmptyStackException();
        }
        T value = (T)items[--size];
        items[size] = null;
        return value;
    }

    public void popSeveralTimes(int count){
        for(int i = 0; i < count; i++){
            pop();
        }
    }

    public void setTop(T element){
        if(isEmpty()){
            throw new EmptyStackException();
        }
        items[size - 1] = element;
    }

    @Override
    public T top() {
        if(isEmpty()){
            throw new EmptyStackException();
        }
        return (T)items[size - 1];
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    public void clear(){
        size = 0;
        items = new Object[maxSize];
    }

    public int getSize() {
        return size;
    }

    public int getMaxSize() {
        return maxSize;
    }
}
